<template>
    <i-select v-model="tag"
              :loading="loading"
              :default="isFirst"
              multiple
              filterable
              remote
              :remote-method="getTagList"
              @on-change="change"
              @on-query-change="searchTag">
        <i-option v-for="v in list" :key="v._id" :value="v._id">{{v.name}}</i-option>
    </i-select>
</template>

<script>
    import API from '../lib/API_PATH'

    export default {
        name: "tag-select",
        props: {
            value: {
                type: Array,
                default() {
                    return []
                }
            },
            isFirst: {
                type: Boolean,
                default: true
            }
        },
        data() {
            return {
                tag: [],
                list: [],
                loading: false,
                name: '',
                page: 1,
                limit: 50,
                defTag: {}
            }
        },
        watch: {
            value: {
                deep: true,
                handler(val) {
                    this.tag = val
                }
            }
        },
        async created() {
            this.tag = this.value
            this.getTagList().then(res => {
                if (this.isFirst && this.value.length === 0) {
                    this.tag = [this.defTag._id]
                }
            })
        },
        methods: {
            // 获取栏目
            async getTagList() {
                this.loading = true
                const params = {
                    name: this.name,
                    page: this.page,
                    limit: this.limit
                }
                try {
                    const {data} = await this.$http(API.TAG, {params})
                    this.list = data.list
                    this.defTag = data.default
                } catch (e) {
                    console.error(e)
                }
                this.loading = false
            },
            // 搜索栏目
            async searchTag(name) {
                this.name = name
                this.page = 1
                this.getTagList()
            },
            change(val) {
                this.$emit('input', this.tag)
            }
        }
    }
</script>

<style scoped>

</style>
